package com.zbkj.service.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zbkj.common.constants.DateConstants;
import com.zbkj.common.constants.SysConfigConstants;
import com.zbkj.common.model.merchant.Merchant;
import com.zbkj.common.model.merchant.MerchantPrint;
import com.zbkj.common.model.order.MerchantOrder;
import com.zbkj.common.model.order.Order;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.common.vo.PrintContentVo;
import com.zbkj.service.service.OrderDetailService;
import com.zbkj.service.service.OrderService;
import com.zbkj.service.service.SystemConfigService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: 大粽子
 * @Date: 2023/9/23 16:41
 * @Description: 描述对应的业务场景
 */
@Component
public class feiEYun {
    public static final String URL = "http://api.feieyun.cn/Api/Open/";//不需要修改

    public static final String USER = "";//*必填*：账号名
    public static final String UKEY = "";//*必填*: 飞鹅云后台注册账号后生成的UKEY 【备注：这不是填打印机的KEY】
    public static final String SN = "";//*必填*：打印机编号，必须要在管理后台里添加打印机或调用API接口添加之后，才能调用API

    @Autowired
    PrintUtil printUtil;

    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SystemConfigService systemConfigService;

    //**********测试时，打开下面注释掉方法的即可,更多接口文档信息,请访问官网开放平台查看**********
    public static void main(String[] args) throws Exception{

        //==================添加打印机接口（支持批量）==================
        //***返回值JSON字符串***
        //正确例子：{"msg":"ok","ret":0,"data":{"ok":["sn#key#remark#carnum","316500011#abcdefgh#快餐前台"],"no":["316500012#abcdefgh#快餐前台#13688889999  （错误：识别码不正确）"]},"serverExecutedTime":3}
        //错误：{"msg":"参数错误 : 该帐号未注册.","ret":-2,"data":null,"serverExecutedTime":37}

        //提示：打印机编号(必填) # 打印机识别码(必填) # 备注名称(选填) # 流量卡号码(选填)，多台打印机请换行（\n）添加新打印机信息，每次最多100行(台)。
//			String snlist = "sn1#key1#remark1#carnum1\nsn2#key2#remark2#carnum2";
//			String method = addprinter(snlist);
//			System.out.println(method);



        //==================方法1.小票机打印订单接口==================
        //***返回值JSON字符串***
        //成功：{"msg":"ok","ret":0,"data":"xxxxxxx_xxxxxxxx_xxxxxxxx","serverExecutedTime":5}
        //失败：{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5}

			//String method1 = print(SN);//该接口只能是小票机使用,如购买的是标签机请使用下面方法2，调用打印
			//System.out.println(method1);



        //==================方法2.标签机专用打印订单接口==================
        //***返回值JSON字符串***
        //成功：{"msg":"ok","ret":0,"data":"xxxxxxx_xxxxxxxx_xxxxxxxx","serverExecutedTime":5}
        //失败：{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5}

//			String method2 = printLabelMsg(SN);//打开注释调用标签机打印接口进行打印,该接口只能是标签机使用，其它型号打印机请勿使用该接口
//			System.out.println(method2);



        //===========方法3.查询某订单是否打印成功=============
        //***返回值JSON字符串***
        //成功：{"msg":"ok","ret":0,"data":true,"serverExecutedTime":2}//data:true为已打印,false为未打印
        //失败：{"msg":"错误描述","ret":非0, "data":null,"serverExecutedTime":7}

//			String orderid = "xxxxxxx_xxxxxxxx_xxxxxxxx";//订单ID，从方法1返回值data获取
//			String method3 = queryOrderState(orderid);
//			System.out.println(method3);



        //===========方法4.查询指定打印机某天的订单详情============
        //***返回值JSON字符串***
        //成功：{"msg":"ok","ret":0,"data":{"print":6,"waiting":1},"serverExecutedTime":9}//print已打印，waiting为打印
        //失败：{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5}

//			String strdate = "2016-11-12";//注意时间格式为"yyyy-MM-dd"
//			String method4 = queryOrderInfoByDate(SN,strdate);
//			System.out.println(method4);



        //===========方法5.查询打印机的状态==========================
        //***返回值JSON字符串***
        //成功：{"msg":"ok","ret":0,"data":"状态","serverExecutedTime":4}
        //失败：{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5}

//			String method5 = queryPrinterStatus(SN);
//			System.out.println(method5);

    }





    //=====================以下是函数实现部分================================================

    private static String addprinter(String snlist){

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user",USER));
        String STIME = String.valueOf(System.currentTimeMillis()/1000);
        nvps.add(new BasicNameValuePair("stime",STIME));
        nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME)));
        nvps.add(new BasicNameValuePair("apiname","Open_printerAddlist"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("printerContent",snlist));

        CloseableHttpResponse response = null;
        String result = null;
        try
        {
            post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if(statecode == 200){
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null){
                    result = EntityUtils.toString(httpentity);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally{
            try {
                if(response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }


    //方法1
    public String print(MerchantOrder order, MerchantPrint merchantPrint, Merchant merchant){
        //标签说明：
        //单标签:
        //"<BR>"为换行,"<CUT>"为切刀指令(主动切纸,仅限切刀打印机使用才有效果)
        //"<LOGO>"为打印LOGO指令(前提是预先在机器内置LOGO图片),"<PLUGIN>"为钱箱或者外置音响指令
        //成对标签：
        //"<CB></CB>"为居中放大一倍,"<B></B>"为放大一倍,"<C></C>"为居中,<L></L>字体变高一倍
        //<W></W>字体变宽一倍,"<QR></QR>"为二维码,"<BOLD></BOLD>"为字体加粗,"<RIGHT></RIGHT>"为右对齐
        //拼凑订单内容时可参考如下格式
        //根据打印纸张的宽度，自行调整内容的格式，可参考下面的样例格式

        // 组装打印内容
        StringBuilder content = new StringBuilder();
        if (StrUtil.isBlank(merchantPrint.getContent())) {
            content.append("<CB>"+merchant.getName()+"</CB><BR>");
            content.append("--------------------------------<BR>");
            content.append("订单编号:" + order.getOrderNo()+"\n");
            content.append("日   期:" + CrmebDateUtil.dateToStr(order.getCreateTime(), DateConstants.DATE_FORMAT)+"\n");
            content.append("电   话:" + (ObjectUtil.isEmpty(order.getUserPhone()) ?"-":order.getUserPhone())+"\n");
            content.append("姓   名:" + (ObjectUtil.isEmpty(order.getRealName())?"-":order.getRealName())+"\n");
            if(order.getShippingType().equals(1)){ // 仅核销订单不打印地址
                content.append("地   址:" + order.getUserAddress()+"\n");
            }
            content.append("订单备注:"+ order.getUserRemark()+"\n");
            content.append("--------------------------------<BR>");
            content.append("名称　　　　　 单价  数量 金额<BR>");
            content.append("--------------------------------<BR>");
            content.append(printUtil.printFormatGoodsList(orderDetailService.getShipmentByOrderNo(order.getOrderNo())));
            content.append("--------------------------------<BR>");
            content.append("赠送积分:"+order.getGainIntegral()+"<BR>");
            content.append("合计:"+ order.getProTotalPrice()+"元，优惠:"+order.getCouponPrice()+"元<BR>");
            content.append("邮费:"+order.getTotalPostage()+"元，抵扣:"+order.getIntegralPrice()+"元<BR>");
            content.append("<L>实际支付:"+ order.getPayPrice() +"元</L><BR>");
        } else {
            PrintContentVo printContentVo = JSON.parseObject(merchantPrint.getContent(), PrintContentVo.class);
            if (printContentVo.getSmallTickerHeader().equals(1)) {
                content.append("<CB>"+merchant.getName()+"</CB><BR>");
                content.append("———————————————<BR>");
            }
            if (printContentVo.getDeliveryInfo().equals(1)) {
                if(order.getShippingType().equals(1)){ // 仅核销订单不打印地址
                    content.append("配送方式:商家配送<BR>");
                } else if (order.getShippingType().equals(2)) {
                    content.append("配送方式:门店自提<BR>");
                } else {
                    content.append("配送方式:虚拟发货<BR>");
                }
                content.append("客户姓名:" + (ObjectUtil.isEmpty(order.getRealName())?"-":order.getRealName())+"<BR>");
                content.append("客户电话:" + (ObjectUtil.isEmpty(order.getUserPhone()) ?"-":order.getUserPhone())+"<BR>");
                if(order.getShippingType().equals(1)){ // 仅核销订单不打印地址
                    content.append("收货地址:" + order.getUserAddress()+"<BR>");
                }
                content.append("———————————————<BR>");
            }
            if (printContentVo.getBuyerRemark().equals(1)) {
                content.append("买家备注:" + order.getUserRemark() +"<BR>");
                content.append("———————————————<BR>");
            }
            if (printContentVo.getProductInfo().equals(1)) {
                content.append("********************************<BR>");
                content.append("商品名称 单价 数量 金额<BR>");
                content.append("********************************<BR>");
                content.append(printUtil.printFormatGoodsList(orderDetailService.getShipmentByOrderNo(order.getOrderNo()))+"<BR>");
                content.append("********************************<BR>");
            }
            if (printContentVo.getFreightInfo().equals(1)) {
                content.append("<RIGHT>运费:"+ order.getPayPostage().toString() +"元</RIGHT><BR>");
            }
            if (printContentVo.getDiscountInfo().equals(1)) {
                BigDecimal discountPrice = order.getCouponPrice().add(order.getSvipDiscountPrice());
                content.append("<RIGHT>优惠:-"+ discountPrice +"元</RIGHT><BR>");
                content.append("<RIGHT>抵扣:-"+ order.getIntegralPrice().toString() +"元</RIGHT><BR>");
                content.append("———————————————<BR>");
            }
            if (CollUtil.isNotEmpty(printContentVo.getPayInfo())) {
                if (printContentVo.getPayInfo().contains(1)) {
                    Order merchatOrder = orderService.getByOrderNo(order.getOrderNo());
                    String payType = "";
                    switch (merchatOrder.getPayType()) {
                        case "weixin":
                            payType = "微信支付";
                            break;
                        case "alipay":
                            payType = "支付宝支付";
                            break;
                        case "yue":
                            payType = "余额支付";
                            break;
                    }
                    content.append("<RIGHT>支付方式:"+ payType +"</RIGHT><BR>");
                }
                if (printContentVo.getPayInfo().contains(2)) {
                    content.append("<RIGHT>实收金额:"+ order.getPayPrice().toString() +"元</RIGHT><BR>");
                    content.append("———————————————<BR>");
                }
            }
            if (CollUtil.isNotEmpty(printContentVo.getOrderInfo())) {
                if (printContentVo.getOrderInfo().contains(1)) {
                    content.append("订单编号:" + order.getOrderNo() +"<BR>");
                }
                if (printContentVo.getOrderInfo().contains(2)) {
                    content.append("下单时间:" + DateUtil.format(order.getCreateTime(), DateConstants.DATE_FORMAT) +"<BR>");
                }
                if (printContentVo.getOrderInfo().contains(3)) {
                    Order merchatOrder = orderService.getByOrderNo(order.getOrderNo());
                    content.append("支付时间:" + DateUtil.format(merchatOrder.getPayTime(), DateConstants.DATE_FORMAT) +"<BR>");
                }
                if (printContentVo.getOrderInfo().contains(4)) {
                    content.append("打印时间:" + DateUtil.date().toString("yyyy-MM-dd HH:mm:ss") +"<BR>");
                }
                content.append("———————————————<BR>");
            }
            if (printContentVo.getCodeUrlSwitch().equals(1) && StrUtil.isNotBlank(printContentVo.getCodeUrl())) {
                String codeUrl = printContentVo.getCodeUrl();
                if (codeUrl.length() > 5) {
                    String substring = codeUrl.substring(0, 5);
                    if (substring.contains("page")) {
                        codeUrl = "http://" + systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_SITE_URL) + codeUrl;
                    }
                }
                content.append("<QR>" + codeUrl + "</QR>");
            }
            if (printContentVo.getBottomNoticeSwitch().equals(1) && StrUtil.isNotBlank(printContentVo.getBottomNotice())) {
                content.append("<C>" + printContentVo.getBottomNotice() + "</C>");
            }
        }

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", merchantPrint.getPrintFeUser()));
        String STIME = String.valueOf(System.currentTimeMillis()/1000);
        nvps.add(new BasicNameValuePair("stime",STIME));
        nvps.add(new BasicNameValuePair("sig",signature(merchantPrint.getPrintFeUser(), merchantPrint.getPrintFeUkey(),STIME)));
        nvps.add(new BasicNameValuePair("apiname","Open_printMsg"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn", merchantPrint.getPrintFeSn()));
        nvps.add(new BasicNameValuePair("content",content.toString()));
        nvps.add(new BasicNameValuePair("times","1"));//打印联数

        CloseableHttpResponse response = null;
        String result = null;
        try
        {
            post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if(statecode == 200){
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null){
                    //服务器返回的JSON字符串，建议要当做日志记录起来
                    result = EntityUtils.toString(httpentity);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally{
            try {
                if(response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }



    //方法2
    private static String printLabelMsg(String sn){

        String content;
        content = "<DIRECTION>1</DIRECTION>";//设定打印时出纸和打印字体的方向，n 0 或 1，每次设备重启后都会初始化为 0 值设置，1：正向出纸，0：反向出纸，
        content += "<TEXT x='9' y='10' font='12' w='1' h='2' r='0'>#001       五号桌      1/3</TEXT><TEXT x='80' y='80' font='12' w='2' h='2' r='0'>可乐鸡翅</TEXT><TEXT x='9' y='180' font='12' w='1' h='1' r='0'>张三先生       13800138000</TEXT>";//40mm宽度标签纸打印例子，打开注释调用标签打印接口打印

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user",USER));
        String STIME = String.valueOf(System.currentTimeMillis()/1000);
        nvps.add(new BasicNameValuePair("stime",STIME));
        nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME)));
        nvps.add(new BasicNameValuePair("apiname","Open_printLabelMsg"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn",sn));
        nvps.add(new BasicNameValuePair("content",content));
        nvps.add(new BasicNameValuePair("times","1"));//打印联数

        CloseableHttpResponse response = null;
        String result = null;
        try
        {
            post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if(statecode == 200){
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null){
                    //服务器返回的JSON字符串，建议要当做日志记录起来
                    result = EntityUtils.toString(httpentity);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally{
            try {
                if(response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }


    //方法3
    private static String queryOrderState(String orderid){

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user",USER));
        String STIME = String.valueOf(System.currentTimeMillis()/1000);
        nvps.add(new BasicNameValuePair("stime",STIME));
        nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME)));
        nvps.add(new BasicNameValuePair("apiname","Open_queryOrderState"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("orderid",orderid));

        CloseableHttpResponse response = null;
        String result = null;
        try
        {
            post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if(statecode == 200){
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null){
                    //服务器返回
                    result = EntityUtils.toString(httpentity);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally{
            try {
                if(response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }



    //方法4
    private static String queryOrderInfoByDate(String sn,String strdate){

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user",USER));
        String STIME = String.valueOf(System.currentTimeMillis()/1000);
        nvps.add(new BasicNameValuePair("stime",STIME));
        nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME)));
        nvps.add(new BasicNameValuePair("apiname","Open_queryOrderInfoByDate"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn",sn));
        nvps.add(new BasicNameValuePair("date",strdate));//yyyy-MM-dd格式

        CloseableHttpResponse response = null;
        String result = null;
        try
        {
            post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if(statecode == 200){
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null){
                    //服务器返回
                    result = EntityUtils.toString(httpentity);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally{
            try {
                if(response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }



    //方法5
    private static String queryPrinterStatus(String sn){

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user",USER));
        String STIME = String.valueOf(System.currentTimeMillis()/1000);
        nvps.add(new BasicNameValuePair("stime",STIME));
        nvps.add(new BasicNameValuePair("sig",signature(USER,UKEY,STIME)));
        nvps.add(new BasicNameValuePair("apiname","Open_queryPrinterStatus"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn",sn));

        CloseableHttpResponse response = null;
        String result = null;
        try
        {
            post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if(statecode == 200){
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null){
                    //服务器返回
                    result = EntityUtils.toString(httpentity);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally{
            try {
                if(response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }


    //生成签名字符串
    private static String signature(String USER,String UKEY,String STIME){
        String s = DigestUtils.sha1Hex(USER+UKEY+STIME);
        return s;
    }
}
